package com.rtx.wms.std.handler.cc.upload;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.wms.customer.common.upload.UploadService;
import com.rtx.wms.std.cc.bean.ApiCCFinish;
import com.rtx.wms.std.cc.service.ApiCCFinishService;
import com.rtx.wms.std.common.bean.WmsConstant;

import cn.hutool.core.util.StrUtil;

@Component
public class CCUploadHandler {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ApiCCFinishService apiCCFinishService;

	@Autowired
	ApplicationContext applicationContext;

	/**
	 * 出库单回传
	 * @param whseid
	 */
	public void handlerOrdersReturn(String whseid,ApiMappingInfoBo bo){
		//获取出库单回传数据
		List<ApiCCFinish> list = selectApifinish("ris_edi");

		for(ApiCCFinish o : list){
			//回传
			UploadService service =(UploadService)applicationContext.getBean(bo.getApimappingcode());
			service.uploadHandle(o);
			//更新状态
			updateApiOrdersfinish("ris_edi",o);
		}
	}


	/**
	 * 更新
	 * @param whseid
	 * @param o
	 */
	protected void updateApiOrdersfinish(String whseid, ApiCCFinish o) {
		try {
			LambdaUpdateWrapper<ApiCCFinish> wrapper = Wrappers.lambdaUpdate();
			wrapper.eq(ApiCCFinish::getSerialkey,o.getSerialkey())
			.set(ApiCCFinish::getEdiflag,o.getEdiflag())
			.set(ApiCCFinish::getEdimsg, StrUtil.sub(o.getEdimsg(),0,400))
			.set(ApiCCFinish::getRtxqueue,o.getRtxqueue() + 1);
			apiCCFinishService.updStatus(whseid,wrapper);

		} catch (Exception e) {
			logger.error("出库单：{}更新回传状态异常",o.getBatchid(),e);
		}
	}

	/**
	 * 获取出库单回传数据
	 * @param whseid
	 * @return
	 */
	protected List<ApiCCFinish> selectApifinish(String whseid){
		LambdaQueryWrapper<ApiCCFinish> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.in(ApiCCFinish::getEdiflag, Arrays.asList(WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG))
		.lt(ApiCCFinish::getRtxqueue,WmsConstant.DEFAULT_COUNT);
		return apiCCFinishService.queryByCondition(whseid,queryWrapper);
	}
}
